//
//  GetInformationViewController.swift
//  E-CycleForShop
//
//  Created by enghou on 17/4/17.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

import UIKit

protocol setImg : NSObjectProtocol{
    func image(img : UIImage,idx : Int) -> Void
    func delete(idx : Int) -> Void
}

class GetInformationViewController: BaseViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    let serial = CameraView.init(frame: CGRect.zero)
    var selectedButton = -1
    var imageData : Array<UIImage> = []
    var param : Dictionary<String,String> = [:]
    override func viewDidLoad() {
        super.viewDidLoad()
        self.naviHide = false
        self.defaultBackButton()
        self.title = "添加身份信息"
        let img = UIImage.init()
        imageData = Array.init(repeating: img, count: 3)
        serial.frame = CGRect.init(x: 10 * YXWidthScale, y: 0, width: 730 * YXWidthScale, height: 316 * YXHeightScale)
        serial.helper = self
        serial.load(title: "添加身份信息", item1: "序列号*", item2: "型 号*")
        self.view.addSubview(serial)
        self.view.backgroundColor = UIColor.colorWithHexString(hex: "f2f2f2")
        
        let cancel = UIButton.init(type: .system)
        cancel.setTitle("跳过", for: .normal)
        cancel.titleLabel?.font = UIFont.boldSystemFont(ofSize: 36 * YXWidthScale)
        cancel.backgroundColor = UIColor.white
        cancel.setTitleColor(UIColor.black, for: .normal)
        cancel.layer.cornerRadius = YXButtonCorner
        cancel.layer.borderColor = UIColor.colorWithHexString(hex: "dfdfdf").cgColor
        cancel.layer.borderWidth = YXHeightScale
        cancel.frame = CGRect.init(x: 30 * YXWidthScale, y: serial.bottom() + 40 * YXHeightScale, width: 325 * YXWidthScale, height: 80 * YXHeightScale)
        cancel.addTarget(self, action: #selector(pops), for: .touchUpInside)
        self.view.addSubview(cancel)
        
        let confirm = UIButton.init(type: .system)
        confirm.setTitle("确定", for: .normal)
        confirm.titleLabel?.font = UIFont.boldSystemFont(ofSize: 36 * YXWidthScale)
        confirm.backgroundColor = UIColor.black
        confirm.setTitleColor(UIColor.white, for: .normal)
        confirm.layer.cornerRadius = YXButtonCorner
        confirm.layer.borderColor = UIColor.colorWithHexString(hex: "dfdfdf").cgColor
        confirm.frame = CGRect.init(x: YXDeviceWidth - 355 * YXWidthScale, y: serial.bottom() + 40 * YXHeightScale, width: 325 * YXWidthScale, height: 80 * YXHeightScale)
        confirm.addTarget(self, action: #selector(uploadImages), for: .touchUpInside)
        self.view.addSubview(confirm)
    }

    @objc func uploadImages() -> Void {
        var dataArr : Array<Data> = []
        for item in imageData {
            if item.size.width > 0 {
                let imgData = UIImageJPEGRepresentation(item, 0.1)
                if imgData != nil {
                    dataArr.append(imgData!)
                }
            }
        }
        if dataArr.count > 0 {
            self.beginAnim()
            Manager.shared().addCompletion(param: param, data: dataArr, success: {(mod) in
                self.endAnim()
                if mod.result == true {
                    self.alertSomeMessage(title: YXAlertTitle, content: "上传图片信息成功!", sureTitle: YXConfirmTitle, cancelTitle: YXCancelTitle, ensureAction: { (alert) in
                        NotificationCenter.default.post(name: NSNotification.Name("addComplete"), object: nil)
                        let _ = self.navigationController?.popToRootViewController(animated: true)
                    }, cancelAction: { (alert) in
                        
                    })
                } else {
                    self.commonAlertMsg(content: mod.msg)
                }
            }, fail: {(code) in
                self.endAnim()
                self.commonAlertMsg(content: YXNetWorkFail)
            })
        } else {
            self.commonAlertMsg(content: "请拍摄或选取照片!")
        }
    }
    
    func handle(idx : UIButton) -> Void {
        //let tag = idx.tag - 1000
        selectedButton = idx.tag - 1000
        self.actionSheet(first: "从相册选取", second: "拍摄", firstHandler: {() in
            self.camera(type: 0)
        }, secondHandler: {() in
            self.camera(type: 1)
        })
    }
    
    func delt(idx : UIButton) -> Void {
        let tag = idx.tag - 1010
        if tag >= 0 && tag < 3 {
            if imageData[tag].size.width > 0 {
                imageData[tag] = UIImage.init()
                self.serial.delete(idx: tag)
            }
        }
    }
    
    func camera(type : Int) -> Void {
        let imgPicker = UIImagePickerController.init()
        imgPicker.delegate = self
        imgPicker.allowsEditing = true
        switch type {
        case 1:
            //
            if UIImagePickerController.isSourceTypeAvailable(.camera) == true {
                imgPicker.sourceType = .camera
            }
            break
        default:
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) == true {
                imgPicker.sourceType = .photoLibrary
            }
            break
            //0
        }
        self.present(imgPicker, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let img = info[UIImagePickerControllerEditedImage] as? UIImage {
            imageData[selectedButton] = img
            self.serial.image(img: img, idx: selectedButton)
        }
        picker.dismiss(animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
